//
//  DataTool.m
//  预购清单
//
//  Created by liujianlong on 2022/10/17.
//

#import "DataTool.h"

@implementation DataTool
+ (void)find:(BOOL)isbasketball complete:(nullable void(^) (NSMutableArray <Record*>*result))block
{
    dispatch_async(dispatch_get_main_queue(), ^{
        ///1，每次查询数据时候，都要根据当前时间戳，从周日到周六，生成本周每天数据
        int stamp = [[NSDate currentTimeStamp:@"yyyy-MM-dd"] intValue];
        NSMutableArray *weekArray = [NSMutableArray array];
        [self initCurrentWeekData:isbasketball stamp:stamp array:weekArray];
        
        ///2，查询全部历史数据
        NSString* where1 = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"isbasketball"),bg_sqlValue(@(isbasketball))];
        NSInteger cout1 = [Record bg_count:nil where:where1];
        
        if (cout1 > 0) {
            ///3，本周数据，再拼接历史数据
            [self bg_find:where1 complete:^(NSMutableArray<Record *> *result) {
                [result addObjectsFromArray:weekArray];
                block(result);
            }];
        }else{
            
            if (block) {
                ///3，本周数据，再拼接新生成的随机数据
                NSMutableArray *result = [self initData:isbasketball];
                [result addObjectsFromArray:weekArray];
                block(result);
            }
        }
    });
}

+ (void)find:(BOOL)isbasketball finish:(BOOL)finish stamp:(NSInteger)stamp complete:(nullable void(^) (NSMutableArray <Record*>*result))block{
    NSDateComponents *date = [NSDate dateOfStamp:stamp];
    NSString* where = [NSString stringWithFormat:@"where %@=%@ and %@=%@ and %@=%@ and %@=%@",
                       bg_sqlKey(@"isbasketball"),bg_sqlValue(@(isbasketball)),
                       //                       bg_sqlKey(@"finish"),bg_sqlValue(@(finish)),
                       bg_sqlKey(@"year"),bg_sqlValue(@(date.year)),
                       bg_sqlKey(@"month"),bg_sqlValue(@(date.month)),
                       bg_sqlKey(@"day"),bg_sqlValue(@(date.day))];
    [self bg_find:where complete:block];
}

+ (void)find:(BOOL)isbasketball finish:(BOOL)finish complete:(nullable void(^) (NSMutableArray <Record*>*result))block{
    NSString* where = [NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"isbasketball"),bg_sqlValue(@(isbasketball)),bg_sqlKey(@"finish"),bg_sqlValue(@(finish))];
    [self bg_find:where complete:block];
}
+ (void)findName:(NSString *)name complete:(nullable void(^) (NSMutableArray <Record*>*result))block{
    NSString *str1 = [NSString stringWithFormat:@" %@=%@ ",bg_sqlKey(@"finish"),bg_sqlValue(@(1))];
    NSString *str2 = [NSString stringWithFormat:@" %@ like '%%%@%%' ",bg_sqlKey(@"home"),name];
    NSString *str3 = [NSString stringWithFormat:@" %@ like '%%%@%%' ",bg_sqlKey(@"from"),name];
    NSString* where = [NSString stringWithFormat:@"where%@and%@or%@",str1,str2,str3];
    [self bg_find:where complete:block];
}

+ (void)findHomeName:(NSString *)name complete:(nullable void(^) (NSMutableArray <Record*>*result))block{
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"home"),bg_sqlValue(name)];
    [self bg_find:where complete:block];
}
+ (void)findFromName:(NSString *)name complete:(nullable void(^) (NSMutableArray <Record*>*result))block{
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"frome"),bg_sqlValue(name)];
    [self bg_find:where complete:block];
}
+ (void)findLike:(BOOL)like complete:(nullable void(^) (NSMutableArray <Record*>*result))block{
    NSString* where = [NSString stringWithFormat:@"where %@=%@ ",bg_sqlKey(@"favorite"),bg_sqlValue(@(like))];
    [self bg_find:where complete:block];
}

+ (void)delete:(Record *)model complete:(nullable void(^) (BOOL success))block{
    NSString* where = [NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"stamp"),bg_sqlValue(@(model.stamp))];
    [Record bg_deleteAsync:nil where:where complete:^(BOOL isSuccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (block) {
                if ([APP.basketRecord containsObject:model]) {
                    [APP.basketRecord removeObject:model];
                }else if ([APP.footRecord containsObject:model]){
                    [APP.footRecord removeObject:model];
                }
                [NotifyTool post:notifyRecordUpdate :nil];
                block(isSuccess);
            }
        });
    }];
}
+ (void)like:(Record*)model complete:(nullable void(^) (BOOL success))block{
    [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (block) {
                block(isSuccess);
            }
        });
    }];
}
+ (void)bg_find:(NSString *)where complete:(nullable void(^) (NSMutableArray <Record*>*result))block{
    [Record bg_findAsync:nil where:where complete:^(NSArray * _Nullable array) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (block) {
                block([NSMutableArray arrayWithArray:array]);
            }
        });
    }];
}

///初始化数据方法1，初始化全部足球，篮球赛事，时间是随机的。
+ (NSMutableArray<Record *>*)initData:(BOOL )isbasketball{
    NSMutableArray *array = isbasketball ? [self basketball] : [self football];
    NSMutableArray *result = [NSMutableArray array];
    for (NSDictionary *dict in array) {
        NSString *league = [[dict allKeys] firstObject];
        NSArray *value = [[dict allValues] firstObject];
        for (NSString *home in value) {
            for (NSString *from in value) {
                if ([home isEqualToString:from]) {break;}
                
                ///随机时间
                int month = (arc4random() % 12) + 1;
                int day = 0;
                if (month == 2) {
                    day = 28;
                }else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12){
                    day = 31;
                }else{
                    day = 30;
                }
                NSDateComponents * date = [NSDate dateOfStamp:[[NSDate currentTimeStamp:@"yyyy-MM-dd"] intValue]];
                day = (arc4random() % day) + 1;
                int hour = (arc4random() % 24);
                int minute = (arc4random() % 60);
                int second = (arc4random() % 60);
                NSString * str = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d",(int)date.year,month,day,hour,minute,second];
                NSLog(@" ========= %@ =  %@ ",isbasketball ? @"篮球比赛":@"足球比赛",str);
                Record *model = [self setupModel:isbasketball h:home f:from l:league stamp:str];
                [result addObject:model];
            }
        }
    }
    ///保存到数据库
    [Record bg_saveOrUpdateArrayAsync:result complete:^(BOOL isSuccess) {
    }];
    
    return result;
}
/// 初始化数据方法2。根据当前时间戳stamp，按照周日到周六的顺序，每天都生成数据。
/// 如果当天已存在数据，则忽略。
+ (NSMutableArray<Record *>*)initCurrentWeekData:(BOOL )isbasketball stamp:(NSInteger)stamp array:(NSMutableArray*)result
{
    NSMutableArray *array = isbasketball ? [self basketball] : [self football];
    
    ///1，随机获取联赛名称，和联赛所有球队
    int index_league = (arc4random() % array.count);
    NSDictionary *dict = array[index_league];
    NSString *league = [[dict allKeys] firstObject];///联赛名称
    NSArray *game = [[dict allValues] firstObject];///联赛所有球队
    
    ///2，从联赛球队中，随机获取主客场球队名称
    int index_home = (arc4random() % game.count);
    int index_fome = (arc4random() % game.count);
    NSString *home = game[index_home];///主场球队名称
    NSString *from = game[index_fome];///客场球队名称
    
    ///3，如果主客队名称相同，则在随机获取一遍
    if ([home isEqualToString:from]) {
        return [self initCurrentWeekData:isbasketball stamp:stamp array:result];
    }
    
    ///4，获取当前的日期信息，并且获取一周的开始，周日的时间戳
    NSDateComponents * dateComp = [NSDate dateOfStamp:stamp];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:stamp];
    int weekday = (int)[NSDate weakDay:date];///当前的日期，距离一周开始(周日)的第几天
    NSInteger week1 = stamp - (weekday - 1) * 86400;///计算出一周开始(周日)的时间戳
    NSInteger temp = week1;
    ///5，从周日循环到周六，生成每天的数据
    while (temp < week1 + 86400 * 7) {
        ///6，获取日，小时，分，秒
        int month = [[NSDate transToDate:@"MM" :temp] intValue];
        int day = [[NSDate transToDate:@"dd" :temp] intValue];
        int hour = (arc4random() % 24);
        int minute = (arc4random() % 60);
        int second = (arc4random() % 60);
        
        ///7，查询数据库中，是否存在本年本月本日的数据
        NSString* where = [NSString stringWithFormat:@"where %@=%@ and %@=%@ and %@=%@ and %@=%@",
                           bg_sqlKey(@"isbasketball"),bg_sqlValue(@(isbasketball)),
                           bg_sqlKey(@"year"),bg_sqlValue(@(dateComp.year)),
                           bg_sqlKey(@"month"),bg_sqlValue(@(dateComp.month)),
                           bg_sqlKey(@"day"),bg_sqlValue(@(day))];
        NSInteger cout = [Record bg_count:nil where:where];
        if (cout > 0){
            NSArray *arr = [Record  bg_find:nil where:where];
            [result addObjectsFromArray:arr];
            temp += 86400;///8，如果存在，则忽略本次循环，进入下次
            continue;
        }else{
            ///8，如果不存在，则以当次循环的年/月/日/时/分/秒，为时间，初始化数据，并且结束本次循环，
            NSString * str = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d",(int)dateComp.year,month,day,hour,minute,second];
            NSLog(@" 本周数据========= %@ =  %@ ",isbasketball ? @"篮球比赛":@"足球比赛",str);
            Record *model = [self setupModel:isbasketball h:home f:from l:league stamp:str];
            [result addObject:model];
            temp += 86400;///结束本次循环，星期天数加1天
        }
    }
    ///9，本次数据存到数据库中
    [Record bg_saveOrUpdateArrayAsync:result complete:^(BOOL isSuccess) {
    }];
    
    return result;
}

///构造数据的参数
+(Record *)setupModel:(BOOL)isbasketball h:(NSString*)home f:(NSString *)from l:(NSString *)league stamp:(NSString *)stampStr{
    Record *model = [Record new];
    model.home = home;
    model.from = from;
    model.isbasketball = isbasketball;
    model.league_name = league;
    model.stamp = [[NSDate tranToStamp:stampStr :@"yyyy-MM-dd HH:mm:ss"] integerValue];
    
    model.fir_score_home = isbasketball ? (arc4random() % 40) + 1 : (arc4random() % 2) + 1;
    model.sec_score_home = isbasketball ? (arc4random() % 40) + 1 : (arc4random() % 2) + 1;
    model.thrd_score_home = isbasketball ? (arc4random() % 40) + 1 : 0;
    model.fth_score_home = isbasketball ? (arc4random() % 40) + 1 : 0;
    model.fir_score_from = isbasketball ? (arc4random() % 40) + 1 : (arc4random() % 2) + 1;
    model.sec_score_from = isbasketball ? (arc4random() % 40) + 1 : (arc4random() % 2) + 1;
    model.thrd_score_from = isbasketball ? (arc4random() % 40) + 1 : 0;
    model.fth_score_from = isbasketball ? (arc4random() % 40) + 1 : 0;
    
    model.total_shoot_home = isbasketball ? (arc4random() % 50) + 1 : (arc4random() % 20) + 1;
    model.total_hit_home = (arc4random() % model.total_shoot_home);
    model.three_shoot_home = isbasketball ? (arc4random() % 25) + 1 : 0;
    model.three_hit_home = isbasketball ? (arc4random() % model.three_shoot_home) : 0;
    model.penalty_shoot_home = isbasketball ? (arc4random() % 25) + 1 : (arc4random() % 5) + 1;
    model.penalty_hit_home = (arc4random() % model.penalty_shoot_home);
    model.total_shoot_from = (arc4random() % (isbasketball?25:5)) + 1;
    model.total_hit_from = (arc4random() % model.total_shoot_from);
    model.three_shoot_from = isbasketball ? (arc4random() % 25) + 1 : 0;
    model.three_hit_from = isbasketball ? (arc4random() % model.three_shoot_from) : 0;
    model.penalty_shoot_from = (arc4random() % (isbasketball?25:5)) + 1;
    model.penalty_hit_from = (arc4random() % model.penalty_shoot_from);
    
    model.REB_home = (arc4random() % (isbasketball?35:5)) + 1;
    model.AST_home = (arc4random() % (isbasketball?35:5)) + 1;
    model.STL_home = (arc4random() % (isbasketball?15:5)) + 1;
    model.BLK_home = (arc4random() % (isbasketball?15:5)) + 1;
    model.FO_home = (arc4random() % (isbasketball?15:5)) + 1;
    model.MIS_home = (arc4random() % (isbasketball?15:5)) + 1;
    model.REB_from = (arc4random() % (isbasketball?35:5)) + 1;
    model.AST_from = (arc4random() % (isbasketball?35:5)) + 1;
    model.STL_from = (arc4random() % (isbasketball?15:5)) + 1;
    model.BLK_from = (arc4random() % (isbasketball?15:5)) + 1;
    model.FO_from = (arc4random() % (isbasketball?15:5)) + 1;
    model.MIS_from = (arc4random() % (isbasketball?15:5)) + 1;
    
    model.rang = isbasketball ? (arc4random() % 20) + 1 : (arc4random() % 2) + 1;
    model.estimate_score = isbasketball ? (arc4random() % 60) + 120 : (arc4random() % 3) + 6;
    
    return  model;
}
+ (NSMutableArray*)football{
    NSArray *league1 = @[@"曼城",@"阿森纳",@"热刺",@"富勒姆",@"利物浦",@"莱斯特城",@"纽卡斯尔联",@"布伦特福德",@"曼联",@"切尔西",@"布莱顿",@"利兹联",@"水晶宫",@"阿斯顿维拉",@"南安普顿",@"埃弗顿",@"西汉姆联",@"伯恩茅斯",@"诺丁汉森林",@"狼队"];
    NSArray *league2 = @[@"皇家马德里",@"巴塞罗那",@"毕尔巴鄂竞技",@"瓦伦西亚",@"马德里竞技",@"皇家社会",@"巴列卡诺",@"赫罗纳",@"比利亚雷亚尔",@"西班牙人",@"皇家贝蒂斯",@"阿尔梅里亚",@"塞尔塔",@"皇家巴拉多利德",@"赫塔菲",@"塞维利亚",@"奥萨苏纳",@"皇家马略卡",@"埃尔切",@"加的斯"];
    NSArray *league3 = @[@"那不勒斯",@"AC米兰",@"拉齐奥",@"国际米兰",@"乌迪内斯",@"尤文图斯",@"亚特兰大",@"萨索洛",@"罗马",@"萨勒尼塔纳",@"博洛尼亚",@"佛罗伦萨",@"都灵",@"蒙扎",@"维罗纳",@"恩波利",@"斯佩齐亚",@"克雷莫纳",@"莱切",@"桑普多利亚"];
    NSArray *league4 = @[@"巴黎圣日耳曼",@"雷恩",@"里尔",@"洛里昂",@"摩纳哥",@"蒙彼利埃",@"里昂",@"特鲁瓦",@"马赛",@"朗斯",@"图卢兹",@"克莱蒙",@"布雷斯特",@"昂热",@"兰斯",@"南特",@"斯特拉斯堡",@"欧塞尔",@"尼斯",@"阿雅克肖"];
    NSArray *league5 = @[@"拜仁",@"法兰克福",@"云达不来梅",@"RB莱比锡",@"柏林联合",@"科隆",@"门兴",@"多特蒙德",@"霍芬海姆",@"美因茨",@"勒沃库森",@"弗赖堡",@"奥格斯堡",@"柏林赫塔",@"沃尔夫斯堡",@"斯图加特",@"沙尔克04",@"波鸿"];
    NSArray *league6 = @[@"武汉三镇",@"山东泰山",@"上海海港",@"上海申花",@"河南嵩山龙门",@"浙江队",@"北京国安",@"梅州客家",@"成都蓉城",@"天津津门虎",@"长春亚泰",@"深圳队",@"大连人",@"沧州雄狮",@"武汉队",@"广州队",@"广州城",@"河北队"];
    
    NSArray *array = @[@{@"英超":league1},@{@"西甲":league2},@{@"意甲":league3},@{@"法甲":league4},@{@"德甲":league5},@{@"中超":league6}];
    return  [NSMutableArray arrayWithArray:array];
}
+(NSMutableArray*)basketball{
    NSArray *league1 = @[@"浙江",@"山西",@"上海",@"同曦",@"新疆",@"山东",@"深圳",@"天津",@"吉林",@"辽宁",@"江苏",@"广州",@"广东",@"广厦",@"北京",@"四川",@"青岛",@"福建",@"北控",@"宁波"];
    NSArray *league2 = @[@"凯尔特人",@"雄鹿",@"黄蜂",@"骑士",@"尼克斯",@"奇才",@"老鹰",@"篮网",@"公牛",@"热火",@"猛龙",@"活塞",@"76人",@"步行者",@"魔术",@"爵士",@"开拓者",@"鹈鹕",@"太阳",@"勇士",@"森林狼",@"快船",@"掘金",@"灰熊",@"马刺",@"独行侠",@"湖人",@"国王",@"雷霆",@"火箭"];
    NSArray *array = @[@{@"CBA":league1},@{@"NBA":league2}];
    return  [NSMutableArray arrayWithArray:array];
}
@end
